/*
 * psSpi.c
 *
 *  Created on: Jul 11, 2021
 *      Author: tau
 */
#include "psSpi.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))


static void pabort(const char *s)
{
	perror(s);
	abort();
}
static const char *device = "/dev/spidev1.0";
static __u32 mode = SPI_MODE_0 ;
static __u8 bits = 8;
static __u32 speed = 10000000;
//static __u32 delay = 0;
static 	int __fd = 0;

int psSpiTransfer(char*  _txBuffer_, unsigned int tlen,char* _rxBuffer_, unsigned int rlen)
{
	int ret;
	struct spi_ioc_transfer tr[2];
	memset(tr,0,sizeof(tr));
	tr[0].tx_buf = (__u64)_txBuffer_;
	tr[0].rx_buf = 0;
	tr[0].len = tlen;

	tr[1].tx_buf = 0;
	tr[1].rx_buf = (__u64)_rxBuffer_;
	tr[1].len = rlen;
	ret = ioctl(__fd, SPI_IOC_MESSAGE(2), &tr);
	if (ret < 1)
		pabort("can't send spi message");
	return ret;
}

int psSpiInit(void)
{
	int ret = 0;
	__fd = open(device, O_RDWR);
	if (__fd < 0)
		pabort("can't open device");
	/*
	 * spi mode
	 */
	ret = ioctl(__fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		pabort("can't set spi mode");
	ret = ioctl(__fd, SPI_IOC_RD_MODE, &mode);
	if (ret == -1)
		pabort("can't get spi mode");
	/*
	 * bits per word
	 */
	ret = ioctl(__fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");
	ret = ioctl(__fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");
	/*
	 * max speed hz
	 */
	ret = ioctl(__fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't set max speed hz");
	ret = ioctl(__fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't get max speed hz");


	printf("spi mode: 0x%x\n", mode);
	printf("bits per word: %d\n", bits);
	printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
	return ret;
}
